<!--
 * @Author: toString muzi_li0323@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString muzi_li0323@163.com
 * @LastEditTime: 2024-06-05 14:37:50
 * @FilePath: /chain-link-api-front/src/views/generateAddress/index.vue
 * @Description: 生成地址
-->
<template>
  <Header>
    <template #title>{{ t('title.GenerateAddress') }}</template>
  </Header>
  <!-- 查询 -->
  <div class="searchBar">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item :label="t('table.ChainName')" style="width:550px; margin-bottom: 0; margin-right: 20px">
          <el-select v-model.trim="queryParams.chainId" :placeholder="t('message.SelectChainName')" clearable>
            <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.chainId" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('generateAddress.Address')" style="width: 150px">
          <el-input v-model.trim="queryParams.address" :placeholder="t('global.PleaseInput') + t('generateAddress.Address')" clearable/>
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" round @click="onSubmit(queryParams.address, queryParams.chainId)">{{ t('button.Search')}}</el-button>
          <el-button type="default" :icon="Refresh" round plain @click="onReset()">{{ t('button.Reset')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  <div class="generate">
    <el-button type="primary" round @click="handleAdd">{{ t('generateAddress.GenerateAddress') }}</el-button>
  </div>
  <div class="table">
    <el-table :data="tableData" size="large" style="width: 100%; height: 600px;" v-loading="loading" border>
      <el-table-column prop="chainName" :label="t('table.ChainName')" width="200" align="center" />
      <el-table-column prop="address" :label="t('generateAddress.Address')" align="center" />
      <el-table-column prop="callBackUrl" :label="t('table.CallBackUrl')" align="center" />
      <el-table-column prop="timestamp" :label="t('table.CallBackTime')" width="auto" align="center">
        <template #default="scope">
          {{ formatTimestamp(scope.row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="t('global.Operation')" width="120" align="center">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleEdit(row)">{{ t('global.Update') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>


  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" status-icon>
      <el-form-item :label="t('table.ChainName')" prop="chainId">
        <el-select v-model.trim="ruleForm.chainId" :placeholder="t('global.PleaseSelect')" :disabled="update">
          <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.chainId" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('table.CallBackUrl')" prop="callBackUrl">
        <el-input v-model.trim="ruleForm.callBackUrl" :placeholder="t('global.PleaseInput')" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">{{ t('global.Cancel') }}</el-button>
        <el-button type="primary" @click="submit">{{ t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import Header from '../layout/header.vue'
import { ref, unref, onMounted, reactive } from "vue";
import { ElTable, ElMessage, ElPagination } from "element-plus";
import { Search, Refresh } from '@element-plus/icons-vue'
import { formatTimestamp } from "../../utils/timeStamp.js";
import { MD5 } from 'crypto-js';
import { getConfigList, generateAddress, getUserAddress, updateCallBackUrl } from '../../require/api'
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)
const isUpdate = ref(false)
const address = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref(t('generateAddress.AddAddress'))
const chainList = ref([])
const update = ref(false)
const rules = reactive({
  chainId: [
    { required: true, message: t('message.SelectChainName'), trigger: 'change', },
  ]
})

const ruleForm = reactive({
  chainId: '',
  callBackUrl: '',
})

onMounted(() => {
  getChainList()
  getList()
})

// 查询参数
const queryParams = reactive([
  {
    address: '',
    chainId: ''
  }
])
// 获取地址列表
async function getList(address, chainId ) {
  try {
    loading.value = true
    const { code, data, msg } = await getUserAddress({
    pageIndex: unref(pageIndex),
    pageSize: unref(pageSize),
    address:address ? address : '',
    chainId: chainId ? chainId : ''
  })
  if (code === 200) {
    tableData.value = data.list
    total.value = data.total
  } else {
    ElMessage.error(msg)
  }
  } catch (error) {
    console.log(error);
  } finally{
    loading.value = false
  }
}

// 获取链列表
async function getChainList() {
  const { data } = await getConfigList()
  chainList.value = data
}

// 生成地址
function handleAdd() {
  isUpdate.value = false;
  dialogTitle.value = t('generateAddress.AddAddress');
  dialogVisible.value = true;
  update.value = false
}

// 修改地址
function handleEdit(row) {
  isUpdate.value = true;
  address.value = row.address
  dialogTitle.value = t('generateAddress.EditAddress');
  ruleForm.callBackUrl = row.callBackUrl
  ruleForm.chainId = row.chainId
  dialogVisible.value = true;
  update.value = true
}


// 搜索方法
const onSubmit = (address, chainId) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(address, chainId);
}

// 清除  queryParams
const onClear = () => {
  queryParams.address= ''
  queryParams.chainId = ''
}

// 重置方法
const onReset = () => {
  onClear();
  getList();
}

// 分页
function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

// 分页
function handleCurrentChange(val) {
  pageIndex.value = val
  getList(queryParams.address, queryParams.chainId)
}

// 关闭
function resetForm() {
  dialogVisible.value = false
  ruleForm.callBackUrl = ''
  ruleForm.chainId = ''
}

// 提交
async function submit() {
  if (!ruleForm.chainId) {
    ElMessage.error(t('message.SelectChainName'))
    return
  }

  const user = sessionStorage.getItem('user');
  const userObject = JSON.parse(user);

  const apiKey = userObject.userInfo.apiKey
  const userId = userObject.userInfo.userId


  const timestamp = Date.now().toString();
  // 生成六位随机数
  const nonce = String(Math.floor(Math.random() * 10000000));
  const temp = unref(chainList).filter(item => item.chainId === ruleForm.chainId)[0]
  const body = JSON.stringify({
    merchantId: userId,
    mainCoinType: temp.udunId,
    callUrl: ruleForm.callBackUrl,
  });
  // 使用 MD5 算法对字符串进行加密，并转换为小写的 32 位十六进制字符串

  const text = body + apiKey + nonce + timestamp;
  const sign = MD5(text).toString()

  let resCode, resMessage;
  if (unref(isUpdate)) {
    const params = {
      callBackUrl: ruleForm.callBackUrl,
      address: unref(address)
    }
    const { code, message } = await updateCallBackUrl(params)
    resCode = code
    resMessage = message
  } else {
    const params = { body, nonce, timestamp, sign }
    const { code, msg } = await generateAddress(params)
    resCode = code
    resMessage = msg
  }

  if (resCode === 200) {
    ElMessage.success(unref(isUpdate) ? t('message.EditSuccess') : t('message.AddSuccess'))
  } else {
    ElMessage.error(resMessage)
  }

  resetForm();
  await getList();
}
</script>
<style lang="less" scoped>

.generate {
  text-align: left;
  margin: 10px
}

// 查询样式
.searchBar {
  :deep(.el-form-item) {
    width: 350px !important;
    margin-right: 20px;
    margin-bottom: 0;
  }
}
</style>